package com.ruyuan.rapid.core.context;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruyuan.rapid.common.enums.ResponseCode;
import com.ruyuan.rapid.common.util.JSONUtil;
import io.netty.handler.codec.http.*;
import lombok.Data;
import org.asynchttpclient.Response;

/**
 * 网关响应封装类
 * @author mac
 */
@Data
public class RapidResponse {

    /**
     * 响应头
     */
    private HttpHeaders responseHeaders = new DefaultHttpHeaders();

    /**
     * 额外的响应头
     */
    private final HttpHeaders extraResponseHeaders = new DefaultHttpHeaders();

    /**
     * 响应内容
     */
    private String content;

    /**
     * 返回响应状态码
     */
    private HttpResponseStatus httpResponseStatus;

    /**
     * 响应对象
     */
    private Response futureResponse;

    private RapidResponse() {
    }

    /**
     * 设置响应头信息
     * @param key
     * @param value
     */
    public void putHeader(CharSequence key, CharSequence value) {
        responseHeaders.add(key, value);
    }

    /**
     * 通过asynchttp response返回构建的RapidResponse
     * @param futureResponse
     * @return
     */
    public static RapidResponse buildRapidResponse(Response futureResponse) {
        RapidResponse rapidResponse = new RapidResponse();
        rapidResponse.setFutureResponse(futureResponse);
        rapidResponse.setHttpResponseStatus(HttpResponseStatus.valueOf(futureResponse.getStatusCode()));
        return rapidResponse;
    }

    /**
     * 返回一个json类型的响应信息, 失败时候使用
     * @param code
     * @param args
     * @return
     */
    public static RapidResponse buildRapidResponse(ResponseCode code, Object... args) {
        ObjectNode objectNode = JSONUtil.createObjectNode();
        objectNode.put(JSONUtil.STATUS, code.getStatus().code());
        objectNode.put(JSONUtil.CODE, code.getCode());
        objectNode.put(JSONUtil.MESSAGE, code.getMessage());
        RapidResponse rapidResponse = new RapidResponse();
        rapidResponse.setHttpResponseStatus(code.getStatus());
        rapidResponse.putHeader(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + ";charset=utf-8");
        rapidResponse.setContent(JSONUtil.toJSONString(objectNode));
        return rapidResponse;
    }

    /**
     * 返回一个json类型的响应信息, 成功时候使用
     * @param data
     * @return
     */
    public static RapidResponse buildRapidResponseObj(Object data) {
        ObjectNode objectNode = JSONUtil.createObjectNode();
        objectNode.put(JSONUtil.STATUS, ResponseCode.SUCCESS.getStatus().code());
        objectNode.put(JSONUtil.CODE, ResponseCode.SUCCESS.getCode());
        objectNode.putPOJO(JSONUtil.DATA, data);
        RapidResponse rapidResponse = new RapidResponse();
        rapidResponse.setHttpResponseStatus(ResponseCode.SUCCESS.getStatus());
        rapidResponse.putHeader(HttpHeaderNames.CONTENT_TYPE,
                HttpHeaderValues.APPLICATION_JSON + ";charset=utf-8");
        rapidResponse.setContent(JSONUtil.toJSONString(objectNode));
        return rapidResponse;
    }
}
